package com.ys.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ys.common.ApiRestResponse;
import com.ys.model.pojo.Equipment;
import com.ys.model.pojo.Factory;
import com.ys.model.pojo.Maintain;
import com.ys.model.request.ComponentChangeReq;
import com.ys.model.request.RepairSearchReq;
import com.ys.model.vo.*;
import com.ys.service.*;
import com.ys.service.impl.PicturesUploadServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/index")
@PropertySource("classpath:application.properties")//读取application.properties文件
public class IndexController {
    @Autowired
    EquipmentService equipmentService;
    @Autowired
    MaintainService maintainService;
    @Autowired
    RepairService repairService;
    @Autowired
    FactoryService factoryService;
    @Autowired
    ComponentService componentService;
    @Autowired
    PicturesUploadServiceImpl picturesUploadService;
    @Autowired
    ChangeService  changeService;

    @Value("${file.path}")
    private String pictureUrl;

    @PostMapping("/allBaseList")
    @ApiOperation("基本数据分页列表 和 根据零件名筛选,web端")
    @ResponseBody
    public ApiRestResponse allBaseList(@Valid @RequestBody RepairSearchReq repairSearchReq) {
        PageInfo page = equipmentService.allBaseList(repairSearchReq);
        return ApiRestResponse.success(page);
    }

    @PostMapping("/getInfoByCname")
    @ApiOperation("基本数据分页列表 和 根据零件名筛选,app端")
    @ResponseBody
    public ApiRestResponse getInfoByCname(@Valid @RequestBody RepairSearchReq repairSearchReq) {
        List<BaseVo> equipmentVo=equipmentService.getInfoByCname(repairSearchReq);

        //将机台、设备等对应放进一个list集合
        List<ECodeVo> eCodeVos = new ArrayList<>();
        String eWorkshop = null;
        String eMachine = null;
        String eName = null;
        String eCode = null;
        int eId = 0;
        if(!equipmentVo.isEmpty()){
            for(BaseVo baseVo : equipmentVo){
                eWorkshop = baseVo.geteWorkshop();
                eMachine = baseVo.geteWorkshop();
                eName = baseVo.geteName();
                eCode = baseVo.geteCode();
                eId = baseVo.geteId();
                ECodeVo eCodeVo =new  ECodeVo(baseVo.getcId(),baseVo.getcName(), baseVo.getcCode(), baseVo.getcType());
                eCodeVos.add(eCodeVo);
            }
        }

        JSONObject object1 = new JSONObject();
        object1.put("eId",eId);
        object1.put("eWorkshop",eWorkshop);
        object1.put("eMachine",eMachine);
        object1.put("eName",eName);
        object1.put("eCode",eCode);
        object1.put("components",eCodeVos);


        return ApiRestResponse.success(object1);
    }

    @PostMapping("/getInfosByECode")
    @ApiOperation(value = "首页-根据设备编码获得信息",notes = "设备编码eCode,设备名称eName,零件名称cName(required),零件编码cCode")
    @ResponseBody
    public ApiRestResponse getInfosByECode(@Valid @RequestBody Equipment  equipment) {
        List<BaseVo> equipmentVo=equipmentService.getInfosByECode(equipment);
        //将机台、设备等对应放进一个list集合
        List<ECodeVo> eCodeVos = new ArrayList<>();
        String eWorkshop = null;
        String eMachine = null;
        String eName = null;
        String eCode = null;
        int eId = 0;
        for(BaseVo baseVo : equipmentVo){
            eWorkshop = baseVo.geteWorkshop();
            eMachine = baseVo.geteWorkshop();
            eName = baseVo.geteName();
            eCode = baseVo.geteCode();
            eId = baseVo.geteId();
            ECodeVo eCodeVo =new  ECodeVo(baseVo.getcId(),baseVo.getcName(), baseVo.getcCode(), baseVo.getcType());
            eCodeVos.add(eCodeVo);
        }

        JSONObject object1 = new JSONObject();
        object1.put("eId",eId);
        object1.put("eWorkshop",eWorkshop);
        object1.put("eMachine",eMachine);
        object1.put("eName",eName);
        object1.put("eCode",eCode);
        object1.put("components",eCodeVos);


        return ApiRestResponse.success(object1);
    }

    @GetMapping("/allCName")
    @ApiOperation(value = "零件名下列列表")
    @ResponseBody
    public ApiRestResponse allCName() {
        List<SearchVo> cNameVo = componentService.allCName();
        JSONObject object = new JSONObject();
        //将机台、设备等对应放进一个list集合
        List<String> cNames =  new ArrayList<>();
        for(SearchVo searchVo : cNameVo){
            cNames.add(searchVo.getcName());
        }
        object.put("cNames",cNames);
        return ApiRestResponse.success(object);
    }

    @PostMapping("/maintain")
    @ApiOperation(value = "维护" ,notes = "cId零件id（require）、mContent维护内容（require）、peopleId人员id（require）、cName零件名（require）")
    @ResponseBody
    public ApiRestResponse maintain(@RequestParam("mContent") String mContent,@RequestParam("cId")  int cId ,@RequestParam("file") MultipartFile[] file,@RequestParam("peopleId")  int peopleId,@RequestParam("cName")  String cName) throws Exception{
       //mod for 当Date中的毫秒数大于500时，存入数据库中时，秒数自动+1，故此处将毫秒数设为0
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND,0);//将毫秒数设为0
        Date date = calendar.getTime();

        Maintain maintain = new Maintain();
        maintain.setcId(cId);
        maintain.setmContent(mContent);
        maintain.setmTime(date);
        maintain.setmPeopleId(peopleId);
        maintain.setcName(cName);
        //添加维护内容
       equipmentService.maintain(maintain);
        //根据维护内容得到维护id
        //Date mTime = maintain.getmTime();
        int mId = maintainService.getMaintainId(date);

        //通过维护id作为外键插进picture表
        String [] n = picturesUploadService.add(file);
        if(n.length>0){
            for (String nn:n) {
                String url = nn;
                maintainService.maintainPictures(url,mId);
            }
        }

        return ApiRestResponse.success();
    }

    @PostMapping("/repair")
    @ApiOperation("维修")
    @ResponseBody
    public ApiRestResponse repair(@RequestParam(value = "cId",required = true)  int cId , @RequestParam(value = "content",required = true) String content ,@RequestParam(value = "file",required = true)MultipartFile[] file,@RequestParam("peopleId")  int peopleId ,@RequestParam("cName")  String cName) throws Exception{
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND,0);//将毫秒数设为0
        Date date = calendar.getTime();


        ComponentChangeReq changeReq = new ComponentChangeReq( cId, content, peopleId);
        changeReq.setTime(date);
        changeReq.setcName(cName);

        equipmentService.repair(changeReq);
        //根据维修内容得到维修id
        int rId = repairService.getRepairId(date);

        //通过维修id作为外键插进picture表
        String [] n = picturesUploadService.add(file);
        if(n.length>0){
            for (String nn:n) {
                String url = nn;
                repairService.repairPictures(url,rId);
            }
        }

        return ApiRestResponse.success();
    }

    @PostMapping("/change")
    @ApiOperation("更换")
    @ResponseBody
    public ApiRestResponse change(@RequestParam(value = "cId",required = false)  int cId ,
                                  @RequestParam(value = "content",required = true)  String content ,@RequestParam(value = "lifespan",required = false)  int lifespan ,
                                  @RequestParam(value = "oldCname",required = false)  String oldCname ,@RequestParam(value = "oldCcode",required = false)  String oldCcode ,@RequestParam(value = "oldCtype",required = false)  String oldCtype ,
                                  @RequestParam(value = "newCname",required = false)  String newCname ,@RequestParam(value = "newCcode",required = false)  String newCcode ,@RequestParam(value = "newCtype",required = false)  String newCtype ,@RequestParam(value = "newFactory",required = false)  String newFactory ,
                                  @RequestParam(value = "file",required = false)MultipartFile[] file ,@RequestParam("peopleId")  int peopleId) throws Exception{
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.MILLISECOND,0);//将毫秒数设为0
        Date date = calendar.getTime();

        ComponentChangeReq oldComponentMsg = null;//旧零件信息
        ComponentChangeReq newComponentMsg = null;//新零件信息

        //1.先根据传回的Cid查找出厂家名称
        int fId = componentService.getFidByCid(cId);
        String fName = factoryService.getFname(fId);
        if(fName==null){
            oldComponentMsg = new ComponentChangeReq( oldCname,oldCcode, oldCtype, "零件厂家为空",content, cId, date,peopleId);
        }else{
            oldComponentMsg = new ComponentChangeReq( oldCname,oldCcode, oldCtype, fName,content, cId, date,peopleId);
        }
        //得到厂家名称后，把旧的零件信息和更新内容插入ys_change
        equipmentService.saveOldComponent(oldComponentMsg);

        //判断新的厂家名字是否存在
        List<Factory> factoryNames = factoryService.getF(newFactory);
        if(!factoryNames.isEmpty()){ //存在
            boolean flag = false;
            for(Factory factory:factoryNames){
                if(factory.getfType().equals("2") ){//存在，且厂家的类型是2
                    //存在，则返回Fid
                    newComponentMsg = new ComponentChangeReq( cId,  newCname,  newCcode,  newCtype,  factory.getfId(),  lifespan ,date);
                    flag = true;
                }//否则
            }
            if(flag == false){ //如果newFactory存在，但是type！=2，则新增厂家
                //先新增新的厂家到ys_factory,set f_type = 2,再返回fId
                factoryService.insertCFName(newFactory);
                Integer newFactoryId = factoryService.getFid(newFactory);
                newComponentMsg = new ComponentChangeReq( cId,  newCname,  newCcode,  newCtype, newFactoryId,  lifespan ,date);
            }
        }else{//不存在，如果newFactory不存在，则新增厂家
            //先新增新的厂家到ys_factory,set f_type = 2,再返回fId
            factoryService.insertCFName(newFactory);
            Integer newFactoryId = factoryService.getFid(newFactory);
            newComponentMsg = new ComponentChangeReq( cId,  newCname,  newCcode,  newCtype, newFactoryId,  lifespan ,date);
        }

        //最后把新的零件信息更新到ys_component
        equipmentService.updateComponent(newComponentMsg);

        //根据更换内容得到更换id
        int changeId = changeService.getChangeId(date);
        System.out.println("得到的id"+changeId);
        //通过维修id作为外键插进picture表
        String [] n = picturesUploadService.add(file);
        if(n.length>0){
            for (String nn:n) {
                String url = nn;
                changeService.changePictures(url,changeId);
            }
        }

        return ApiRestResponse.success();
    }

}
